<template>
  <div class="blogrollIndex" id="blogrollIndex">
    <a-button
      type="primary"
      class="addButton"
      :disabled="!btnPerm.includes('creatAble')"
      @click="addGroupingRecord"
      >新建分组</a-button
    >
    <treeTable
      :columns="columns.groupingColumns"
      :dataSource="resData.records"
      :isSelect="true"
      :scroll="scroll"
      ref="tagBaseTables"
      :isShowPagination="isShowPagination"
      :showCheckDelete="showCheckDelete"
      :total="resData.total"
      @changePage="changePage"
    >
      <template #bodyCell="{ column, text, record }">
        <template v-if="column.dataIndex === 'oparation'">
          <a href=""></a>
        </template>
        <template v-if="column.dataIndex === 'oparation'">
          <a
            class="eidtRecords"
            :class="{ disable: !btnPerm.includes('friendlyLinkAble') }"
            @click="linkRecords(record)"
            >友情链接</a
          >
          <a
            class="eidtRecords"
            :class="{ disable: !btnPerm.includes('editAble') }"
            @click="editRecords(record.id)"
            >编辑</a
          >
          <a-popconfirm
            placement="topRight"
            :disabled="!btnPerm.includes('deleteAble')"
            @confirm="confirmDelete([record.id])"
          >
            <template #title>
              <p style="width: 197px">是否确定删除该分组？分组内友情链接将同步删除</p>
            </template>
            <a :class="{ disable: !btnPerm.includes('deleteAble') }">删除</a>
          </a-popconfirm>
        </template>
      </template>
      <template #otherOpration>
        <a-button
          :style="{ 'margin-left': '8px' }"
          @click="deleteSelectedAll"
          :disabled="!rowSelection.length || !btnPerm.includes('deleteAble')"
          >删除</a-button
        >
      </template>
    </treeTable>
    <base-modal
      :width="modAlProps.width"
      :isVisible="isVisible"
      :title="modAlProps.title"
      :buttons="buttons"
      :cancleText="'关闭'"
      @handleCancle="handleCancle"
      @handleOk="handleOk"
      class="addCorrelation"
      v-if="isVisible"
    >
      <template v-slot:body>
        <a-form
          name="advanced_search"
          autoComplete="off"
          class="ant-advanced-search-form"
          :model="formState"
          ref="columnFrom"
        >
          <a-form-item
            label="分组名称"
            name="typeName"
            :rules="[{ required: true, trigger: 'blur', validator: validatePass }]"
          >
            <a-input
              v-model:value="formState.typeName"
              placeholder="请输入分组名称"
              show-count
              :maxlength="50"
              allow-clear
            ></a-input>
          </a-form-item>
        </a-form>
      </template>
    </base-modal>
  </div>
</template>

<script lang="ts" setup>
import {
  ref,
  reactive,
  onMounted,
  nextTick,
  createVNode,
  computed,
  watch,
  toRef,
} from "vue";
import treeTable from "@/components/table/baseTable.vue";
import columns from "@/components/table/tableConfig/tableColumn/configTableColumn";
import baseModal from "@/components/modal/baseModal.vue";
import tableToolTip from "@/components/table/tableToolTip.vue";
import { checkuserManage } from "./formRuler";
import { scrollType, configDataType } from "@/type.d";
import { getTableScroll, inintDrag } from "@/components/table/tableConfig/table";
import { Modal, message } from "ant-design-vue";
import request from "@/api/index";
import { useRouter } from "vue-router";
import { routerPerm } from "@/utils/common";
const btnPerm = ref<any[]>([]);
interface dataSourceType {
  [propName: string | number]: any;
}
const router = useRouter();
const columnFrom = ref<any>("columnFrom");
const isShowPagination = ref<boolean>(true); // 是否需要配分页器
const showCheckDelete = true; // 是否需要分页器中的自定义
const isVisible = ref<boolean>(false);
let resData = reactive<configDataType>({ total: 0, size: 10, records: [] });
let scroll: scrollType = reactive({ y: "", isFixed: false });
const tagBaseTables = ref<any>(null);
let rowSelection = ref<(string | number)[]>([]);
const dragEnd = ref<any>({});
let datas = reactive<dataSourceType>({});
const modAlProps = reactive<dataSourceType>({
  width: "M",
  title: "新建分组",
});
let buttons = ref<dataSourceType[]>([
  //   {
  //     text: "保存并继续新建",
  //     cz: "bcandxj",
  //     keepAlive: true,
  //   },
  {
    text: "保存",
    cz: "bc",
    keepAlive: true,
  },
]);

const formState = ref<dataSourceType>({
  typeName: "",
});
let validatePass = async (_rule: any, value: any) => {
  if (value === "") {
    return Promise.reject("请输入分组名称！");
  } else {
    let res = await request[`fetchSysLinkTypeCheckName`]({
      name: value,
      id: formState.value.id,
    });
    if (!res) {
      return Promise.reject(`分组名重复！`);
    } else {
      return Promise.resolve();
    }
  }
};
watch(
  () => dragEnd.value,
  (newVal, oldVal) => {
    if (newVal.id && newVal.id != newVal.toId) {
      request
        .fetchSysLinkTypeSort(newVal)
        .then((res: any) => {
          if (res.code == "00000 00000") {
            message.success(res.message);
          } else {
            message.error(res.message);
          }
          fetchSysLinkTypePage();
        })
        .catch((err: any) => {
          throw new Error(err);
        });
    }
  },
  { deep: true }
);
//computed
rowSelection = computed(() => {
  return tagBaseTables.value.selectedRowKeys;
});
const fetchSysLinkTypePage = async () => {
  const params = {
    pageNumber: datas.pageNumber || 1,
    pageSize: datas.pageSize || 10,
  };
  const data = await request.fetchSysLinkTypePage(params);
  resData.total = data.total;
  resData.records = [];
  resData.records =
    data.records.length &&
    data.records.map((item: dataSourceType, index: number) => {
      item.sortNum = index + 1;
      return item;
    });
  tagBaseTables.value.selectedRowKeys = [];
  nextTick(() => {
    let obj = getTableScroll(74, "blogrollIndex");
    scroll.y = obj.y;
    scroll.isFixed = obj.isFixed;
    dragEnd.value = {};
    setTimeout(() => {
      inintDrag("blogrollIndex", resData, "records", dragEnd);
    }, 40);
  });
};
const changePage = (data: { pageCurrent: any; pageSize: any }) => {
  datas = {
    pageNumber: data.pageCurrent,
    pageSize: data.pageSize,
  };
  fetchSysLinkTypePage();
};
// 添加分组
const addGroupingRecord = () => {
  formState.value = {
    typeName: "",
    id: "",
  };
  buttons.value = [
    {
      text: "保存并继续新建",
      cz: "bcandxj",
      keepAlive: true,
    },
    {
      text: "保存",
      cz: "bc",
      keepAlive: true,
    },
  ];
  isVisible.value = true;
};
// 编辑
const editRecords = async (id: any) => {
  if (!btnPerm.value.includes("editAble")) return;
  isVisible.value = true;
  modAlProps.title = "编辑分组";
  buttons.value = [
    {
      text: "保存",
      cz: "bc",
      keepAlive: true,
    },
  ];
  const data = await request.fetchSysLinkTypeDetail({ id: id });
  formState.value = {
    typeName: data.typeName,
    id: data.id,
  };
};

const handleOk = async (msg: dataSourceType) => {
  columnFrom.value
    .validate()
    .then(() => {
      if (formState.value.id) {
        console.log("sdfasdf");
        request
          .fetchSysLinkTypeUpdate(formState.value)
          .then((res: any) => {
            if (res.code == "00000 00000") {
              fetchSysLinkTypePage();
              isVisible.value = false;
              formState.value = {};
              message.success(res.message);
            } else {
              message.error(res.message);
            }
          })
          .catch((err: any) => {
            throw new Error(err);
          });
      } else {
        request
          .fetchSysLinkType(formState.value)
          .then((res: any) => {
            if (res.code == "00000 00000") {
              fetchSysLinkTypePage();
              if (msg.cz == "bc") {
                isVisible.value = false;
              }
              formState.value.typeName = "";
              message.success(res.message);
            } else {
              message.error(res.message);
            }
          })
          .catch((err: any) => {
            throw new Error(err);
          });
      }
    })
    .catch(() => {});
};
const handleCancle = async (msg: dataSourceType) => {
  isVisible.value = false;
};

// 友情链接
const linkRecords = async (item: dataSourceType) => {
  if (!btnPerm.value.includes("friendlyLinkAble")) return;
  router.push({
    path: "/config/blogroll/blogroll",
    name: "友情链接",
    query: {
      id: item.id,
      name: item.typeName,
    },
  });
};
// 删除
const confirmDelete = async (datas: any) => {
  request
    .fetchSysLinkTypeDelete({ ids: datas })
    .then((res: any) => {
      if (res.code == "00000 00000") {
        fetchSysLinkTypePage();
        message.success(res.message);
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};
// 删除多个
const deleteSelectedAll = async (item: any) => {
  Modal.confirm({
    content: "是否确定删除选中的分组？分组内友情链接将同步删除",
    centered: true,
    icon: createVNode("i", {
      class: "iconfont icon-warn warning_ICON",
    }),
    cancelText: "取消",
    okText: "确定",
    onOk: async () => {
      confirmDelete(tagBaseTables.value.selectedRowKeys);
    },
    onCancel() {},
  });
};
onMounted(() => {
  btnPerm.value = routerPerm();
  fetchSysLinkTypePage();
});
</script>

<style lang="less" scoped>
.blogrollIndex {
  background-color: #fff;
  padding: 16px;
  height: calc(100% - 72px);
  //   overflow: hidden;
  //   display: flex;
  //   flex-direction: column;

  .addButton {
    margin-bottom: 16px;
  }

  .eidtRecords {
    margin-right: 16px;
  }
}

::v-deep(.ant-table-body) {
  cursor: move;
}

:deep(.ant-form-item:last-child) {
  margin-bottom: 0;
}
</style>
